using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;

namespace etbTOEIC
{
	/// <summary>
	/// Summary description for DataBase.
	/// </summary>
	public class DataBase
	{
		public static OleDbConnection conn;
		
		public static string strConn = "Data Source=" + System.Windows.Forms.Application.StartupPath + "\\dbTOEFL.mdb;Provider=Microsoft.Jet.OLEDB.4.0";
		
		public DataBase()
		{
					
		}

		
		public static Boolean OpenCn()
		{
			conn = new OleDbConnection(strConn);
			
			
			try
			{
				conn.Open();
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}

		public static void CloseCn()
		{
			if (conn != null)
			{
				conn.Close();
			}
		}
		
				
		public static Boolean ExecuteQuery(string strsql, ref DataSet ds)
		{
			
			
			//Mo ket noi
			if (!OpenCn())
			{
				return false;
			}
			try
			{
				OleDbCommand cmd = new OleDbCommand(strsql, conn);
				OleDbDataAdapter da = new OleDbDataAdapter(cmd);
				
				
				// Thuc thi lay du lieu
				da.Fill(ds);

				// Dong ket noi
				CloseCn();
				return true;
			}
			catch(Exception)
			{
				return false;
			}
		}
		public static Boolean ExecuteQuery(string strsql, ref Object[] obj)
		{
			
			
			//Mo ket noi
			if (!OpenCn())
			{
				return false;
			}
			try
			{
				OleDbCommand cmd = new OleDbCommand(strsql, conn);
				OleDbDataReader dr = cmd.ExecuteReader();
				if(dr.Read())
                    dr.GetValues(obj);
				// Dong ket noi
				CloseCn();
				return true;
			}
			catch(Exception)
			{
				return false;
			}
		}
		
		public static Boolean ExecuteNonQuery(string strsql)
		{
			//Mo ket noi
			if (!OpenCn())
			{
				return false;
			}
			try
			{
				OleDbCommand cmd = new OleDbCommand(strsql, conn);

				//Thuc thi
				int nReturn = cmd.ExecuteNonQuery();
				if (nReturn<=0)
				{
					throw new Exception();
				}
				//Dong ket noi
				CloseCn();
				return true;
			}
			catch(Exception)
			{
				return false;
			}
			
		}
		public static Boolean ExecuteScalar(string strsql, ref int nReturn)
		{
			//Mo ket noi
			if (!OpenCn())
			{
				return false;
			}
			try
			{
				OleDbCommand cmd = new OleDbCommand(strsql, conn);

				//Thuc thi
				nReturn = (int) cmd.ExecuteScalar();
				if (nReturn<0)
				{
					throw new Exception();
				}
				//Dong ket noi
				
				CloseCn();
				return true;
			}
			catch(Exception)
			{
				return false;
			}
			
		}
		//cac ham doc du lieu dat tai day
	}
}
